package org.elfen.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.elfen.common.Token;
import org.elfen.common.base.BaseController;
import org.elfen.common.entity.Login;
import org.elfen.common.result.ResultUtil;
import org.elfen.common.security.SecurityUtil;
import org.elfen.common.util.DataUtil;
import org.elfen.redis.service.RedisService;
import org.elfen.sys.entity.SysUser;
import org.elfen.sys.facade.SysUserBiz;
import org.elfen.sys.facade.TokenBiz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value = "身份认证服务接口", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping("/token")
public class TokenController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(TokenController.class);
	
	@Autowired
	private SysUserBiz sysUserBiz;
	@Autowired
	private TokenBiz tokenBiz;
	@Autowired
	private RedisService redisService;
	
	// 登录
	@ApiOperation(value = "用户身份认证服务")
	@PostMapping(value = "/user")
	public Object user(
			@ApiParam(required = true, value = "登录帐号和密码") @RequestBody @Valid Login user,
			BindingResult br) {
		if(br.hasErrors()){
			List<ObjectError> list = br.getAllErrors();
			String msg = list.get(0).getDefaultMessage();
			return ResultUtil.renderError(msg);
		}
		
		SysUser sysUser = sysUserBiz.selectUserByUserName(user.getUserName());
        if(DataUtil.isNotEmpty(sysUser)){
        	if(sysUser.getIsEnable() == 0){//是否启用:0-启用，1-禁用
                 if (sysUser.getUserPassword().equals(SecurityUtil.encryptPassword(user.getPassword()))) {
                	 try {
                		 Map<String,Object> resultMap = new HashMap<String,Object>();
                		 resultMap.put("sysUser", sysUser);
                		 
                		 Token token = tokenBiz.getTokenInfo(sysUser.getId(),sysUser.getUserName());
                		 String tokenKey = token.getTokenKey();
						 redisService.saveToken2Redis(token);
						 resultMap.put("token", tokenKey);
						 
						 return ResultUtil.renderSuccess("身份认证信息获取成功！",resultMap);
                	 } catch (Exception e) {
                		 log.error("生成并保存Token信息出现异常！", e);
                		 return ResultUtil.renderError("身份认证信息获取失败！");
                	 }
                 }
                 return ResultUtil.renderError("账号或密码错误！");
        	}else {
        		return ResultUtil.renderError("账号已被冻结！");
            }
        }else {
            log.warn("不存在该用户: {}", user.getUserName());
            return ResultUtil.renderError("账号或密码错误！");
        }
		
	}
	
	// 登出
	@ApiOperation(value = "退出系统")
	@ApiImplicitParam(name="authorization",value="header中的token数据",required=true,paramType="header",dataType="String")
	@PostMapping(value = "/logout")
	public Object userLogout(HttpServletRequest request) {
		String tokenKey = request.getHeader("authorization");
		if(DataUtil.isEmpty(tokenKey)){
			return ResultUtil.renderError("请先获取身份认证信息！");
		}
		
		try {
			redisService.deleteToken2Redis(tokenKey);
			
			return ResultUtil.renderSuccess("退出系统成功！");
		} catch (Exception e) {
			log.error("删除Token出现异常！", e);
			return ResultUtil.renderError("退出系统失败！");
		}
	}

	// 注册
	@ApiOperation(value = "用户注册服务")
	@PostMapping(value = "/userRegister")
	public Object userRegister(@RequestBody  @Valid SysUser sysUser,BindingResult br) {
		if(br.hasErrors()){
			List<ObjectError> list = br.getAllErrors();
			String msg = list.get(0).getDefaultMessage();
			return ResultUtil.renderError(msg);
		}
		
		Integer isEnable = sysUser.getIsEnable();
		if(DataUtil.isEmpty(isEnable)){
			return ResultUtil.renderError("‘是否启用’字段值不能为空！");
		}
		if(!DataUtil.pattern("^[0|1]$", isEnable+"")){
			return ResultUtil.renderSuccess("‘是否启用’字段值只能是0或1（0-启用，1-禁用）！");
		}
		
		SysUser s1 = sysUserBiz.selectUserByUserName(sysUser.getUserName());
		if(DataUtil.isNotEmpty(s1)){
			return ResultUtil.renderError("账号["+sysUser.getUserName()+"]已经被注册了！");
		}
		
		s1 = null ;
		s1 = sysUserBiz.selectUserByNick(sysUser.getUserNick());
		if(DataUtil.isNotEmpty(s1)){
			return ResultUtil.renderError("昵称["+sysUser.getUserNick()+"]已经被使用了！");
		}
		
		s1 = null ;
		s1 = sysUserBiz.selectUserByQQ(sysUser.getUserQQ());
		if(DataUtil.isNotEmpty(s1)){
			return ResultUtil.renderError("QQ号["+sysUser.getUserQQ()+"]已经被绑定了！");
		}
		if(DataUtil.isNotEmpty(sysUser.getTaobao())){
			s1 = null;
			s1 = sysUserBiz.selectUserByTabao(sysUser.getTaobao());
			if(DataUtil.isNotEmpty(s1)){
				return ResultUtil.renderError("淘宝账号["+sysUser.getTaobao()+"]已经被绑定了！");
			}
		}	
		
		sysUser.setUserPassword(SecurityUtil.encryptPassword(sysUser.getUserPassword()));
		setCreateInfo(sysUser);
		if(DataUtil.isNotEmpty(sysUser.getId())){
			sysUser.setId(null);
		}
		sysUserBiz.insertUser(sysUser);
		
		return ResultUtil.renderSuccess("用户注册成功！");
	}
	
}
